//
//  String+Extension.swift
//  pBox
//
//  Created by TianChenIMac1 on 2019/9/27.
//  Copyright © 2019 skymesh. All rights reserved.
//

import UIKit
import CommonCrypto

//自定义域名
public let tcDomain = "skymesh://"


extension String {
    
    
    var length: Int {
        return self.count
    }
    
    subscript (i: Int) -> String {
        return self[i ..< i + 1]
    }
    
    func substring(fromIndex: Int) -> String {
        return self[min(fromIndex, length) ..< length]
    }
    
    func substring(toIndex: Int) -> String {
        return self[0 ..< max(0, toIndex)]
    }
    
    subscript (r: Range<Int>) -> String {
        let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound))))
        let start = index(startIndex, offsetBy: range.lowerBound)
        let end = index(start, offsetBy: range.upperBound - range.lowerBound)
        return String(self[start ..< end])
    }
    
    var md5: String {
        guard let data = self.data(using: .utf8) else {
            return self
        }
        var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
        #if swift(>=5.0)
        _ = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
            return CC_MD5(bytes.baseAddress, CC_LONG(data.count), &digest)
        }
        #else
        _ = data.withUnsafeBytes { bytes in
            return CC_MD5(bytes, CC_LONG(data.count), &digest)
        }
        #endif
        
        return digest.map { String(format: "%02x", $0) }.joined()
    }
    
    //动态计算字符串高度
    func getLabHeigh(font:UIFont,width:CGFloat) -> CGSize {
        
        let size = CGSize(width: width, height: 900)
        
        let dic = NSDictionary(object: font, forKey: NSAttributedString.Key.font as NSCopying)
        
        let strSize = self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as! [NSAttributedString.Key : Any], context:nil).size
        
        return strSize
        
    }
    
    
    func index(of string: String, options: CompareOptions = .literal) -> Index? {
        return range(of: string, options: options)?.lowerBound
    }
    func endIndex(of string: String, options: CompareOptions = .literal) -> Index? {
        return range(of: string, options: options)?.upperBound
    }
    func indexes(of string: String, options: CompareOptions = .literal) -> [Index] {
        var result: [Index] = []
        var start = startIndex
        while let range = range(of: string, options: options, range: start..<endIndex) {
            result.append(range.lowerBound)
            start = range.upperBound
        }
        return result
    }
    func ranges(of string: String, options: CompareOptions = .literal) -> [Range<Index>] {
        var result: [Range<Index>] = []
        var start = startIndex
        while let range = range(of: string, options: options, range: start..<endIndex) {
            result.append(range)
            start = range.upperBound
        }
        return result
    }
    
    func setSpaceWith(text :String,spacing :CGFloat){
        
        let attributedString = NSMutableAttributedString.init(string: text, attributes: [NSAttributedString.Key.kern:spacing])
    }
    
    
    //MARK:-获取字符串位置
    func getStringRange(from range :Range<String.Index>) -> NSRange?{
        let utf16view = self.utf16
        if let from = range.lowerBound.samePosition(in: utf16view), let to = range.upperBound.samePosition(in: utf16view) {
            
            return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from), utf16view.distance(from: from, to: to))
        }
        
        return nil
        
    }
    

    
    // rangeString :需要检索的字符, 改变字符串的指定位置的颜色 字体大小
    func getAttributesFrome(rangeString:String,attrs:[NSAttributedString.Key:Any]) -> NSMutableAttributedString?{
        
        let attributedString = NSMutableAttributedString(string: self)
        
        let ranges = self.ranges(of: rangeString)
        
        for  item in ranges {
            
            guard let range = self.getStringRange(from: item) else {return attributedString}
            
            debugPrint(range)
            attributedString.addAttributes(attrs, range: range)
            
        }
//
//        // 改变颜色 和 字体大小
//        attributedString.addAttributes(attrs, range: nsRange)
        return attributedString
    }
    
    func subString(_ from: Int) -> String? {
        if from >= self.count { return nil }
        
        let startIndex = self.index(self.startIndex, offsetBy: from < 0 ? 0 : from)
        return String(self[startIndex...])
    }
    
    func range(_ subString:String, reverse:Bool=false) -> Range<String.Index>? {
        return self.range(of: subString, options: (reverse ? String.CompareOptions.backwards : String.CompareOptions.literal), range: Range.init(NSRange.init(location: 0, length: self.count), in: self), locale: Locale.current)
    }
    
    func toRange(_ range: NSRange) -> Range<String.Index>? {
        guard let from = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex) else { return nil }
        guard let to = utf16.index(from, offsetBy: range.length, limitedBy: utf16.endIndex) else { return nil }
        return from..<to
    }
    
    
}

extension URL {
    func tcString() -> String {
        var absoluteString = self.absoluteString
        if absoluteString.hasPrefix(tcDomain) {
            if let range = absoluteString.range(of: tcDomain) {
                absoluteString = absoluteString.replacingOccurrences(of: tcDomain, with: "", options: .caseInsensitive, range: range)
            }
        }
        
        return absoluteString
    }
}
